package br.com.simora.crawler;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Date;

import javax.inject.Named;

import org.apache.log4j.Logger;

import br.com.simora.musica.Artista;
import br.com.simora.musica.Musica;
import br.com.simora.radio.RadioEnum;

@Named("cidadefm")
public class RadioCidadeFMCrawler extends AbstractCrawler {
	private static Logger logger = Logger.getLogger(RadioCidadeFMCrawler.class);
	private static String URL = "http://www.radiocidade.fm/tools/xml_radios_index.html?";
	
	@Override
	public void recuperaInfo() {
		String url = URL +  new Date().getTime();
		//logger.debug(url);
		recuperador.setUrl(url, "xml");
		pagina = recuperador.getPagina();
		String[] itensConteudo = pagina.getConteudo().split(":");
		String artistaNome = "";
		String musicaNome = "";
		if(itensConteudo.length > 0){
			String[] dados = itensConteudo[1].split("-");
			if(dados.length > 0){
				if(dados[1] != null && !"".equals(dados[1].trim())){
					try {
						artistaNome = new String(dados[1].trim().getBytes(Charset.forName(pagina.getContentType())), pagina.getContentType())
						.replace("}", "").replace("\\u00c3", "�").replace("\\u00b4", "'").replace("\\u00c1", "�")
						.replace("\\u00ea", "�").replace("\\u00d3", "�").replace("\\u00e7", "�").replace("\"", "");
						artista = new Artista();
						artista.setNome(artistaNome);
					} catch (UnsupportedEncodingException e) {
						logger.debug(e.getMessage());
						e.printStackTrace();
					}
				}
				if(dados[0] != null && !"".equals(dados[0].trim())){
					try {
						musicaNome = new String(dados[0].trim().getBytes(Charset.forName("8859_1")), "UTF8").replace("}", "").replace("\\u00c3", "�").replace("\\u00b4", "'")
								.replace("\\u00c1", "�").replace("&#039;", "'")
								.replace("\\u00ea", "�").replace("\\u00d3", "�").replace("\\u00e7", "�").replace("\"", "");
						musica = new Musica();
						musica.setNome(musicaNome);
					} catch (UnsupportedEncodingException e) {
						logger.debug(e.getMessage());
						e.printStackTrace();
					}
				}
			}
		}
		logger.debug(artistaNome + " - " + musicaNome);
	}

	@Override
	public void setRadioNome() {
		this.radioNome = RadioEnum.cidade.getNome();
	}

}